<?php
namespace modules;
use \phiction\link;
use \phiction\array_utils as arr;

class page
{
    static function title(): string
    {
        return "博客";
    }

    static function home(): string
    {
        return "/post/list";
    }

    static function skeleton($html, array $args): array
    {
        $title = $args['TITLE'];
        if (arr::get($args, 'SUBTITLE', $subtitle)) $title .= ' - ' . $subtitle;

        return $html->mark([ 'html',
            [ 'head',
                [ '/meta', 'charset' => 'utf-8' ],
                [ '/meta', 'name' => 'viewport', 'content' => 'width=device-width, initial-scale=1' ],
                [ 'title', $title ],
                self::link_css("index.css"),
                self::link_css("font-awesome.min.css"),
                self::link_js("jquery-2.2.3.min.js"),
                self::link_js("index.js"),
            ],
            [ 'body',
                [ 'div', 'class' => 'center-wrapper',
                    self::header($html, $args),
                    [ 'div', 'class' => 'content-wrapper', $args['BODY'] ],
                ],
            ],
        ]);
    }

    static function bad_page($html, array $args): array
    {
        $args['TITLE'] = "出错啦";
        unset($args['SUBTITLE']);
        $args['BODY'] = $html->mark(['.',
            [ 'div', 'class' => 'error-title', "出错啦" ],
            [ 'pre', $args['BODY'] ],
        ]);
        return self::skeleton($html, $args);
    }

    static function no_such_page($msg): string
    {
        return "404: $msg";
    }

    static function login(): string
    {
        return "/auth/login";
    }

    static function denied(): string
    {
        return "/auth/denied";
    }

    static function api_result_filter($result, array $args)
    {
        if (array_key_exists('token', $args)) {
            $secure = $args['HTTPS'];
            setcookie('token', $args['token'], 1 << 32, "/", "", $secure, true);
        }
        return $result;
    }

    static function page_result_filter($result, array $args)
    {
        if (array_key_exists('token', $args)) {
            $secure = $args['HTTPS'];
            setcookie('token', $args['token'], 1 << 32, "/", "", $secure, true);
        }
        return $result;
    }

    private static function link_css(string $css)
    {
        return [ '/link', 'rel' => 'stylesheet', 'href' => link::static("css/$css") ];
    }

    private static function link_js(string $js, bool $defer=false)
    {
        return [ 'script', 'src' => link::static("js/$js"), 'defer' => $defer ];
    }

    private static function header($html, array $args): array
    {
        $result = [
            'header',
            ['a', 'href' => '/', 'class' => 'site-name block', "博客"],
        ];
        if (arr::get($args, 'HEADER-CONTROL', $controls)) $result[] = $controls;
        return $html->mark($result);
    }
}

